﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Web;

namespace Crucible.Models
{
    public class ArgumentConnection : DbContext
    {

        public ArgumentConnection()
            : base()
        {
            //this.Configuration.LazyLoadingEnabled = false;
        }

        public DbSet<Node> Nodes { get; set; }

        public DbSet<NodeLink> NodeLinks { get; set; }

        //public DbSet<Persuasive> Persuasives { get; set; }

        //public DbSet<Originator> Originators { get; set; }

        //public DbSet<Source> Sources { get; set; }

        public DbSet<UserProfile> UserProfiles { get; set; }

        public DbSet<UserData> UserData { get; set; }

        public DbSet<NodeVote> AssertionVotes { get; set; }

        public DbSet<CommentVote> CommentVotes { get; set; }

        public DbSet<Comment> Comments { get; set; }

        public DbSet<Fallacy> Fallacies { get; set; }


        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            base.OnModelCreating(modelBuilder);

            modelBuilder.Entity<Comment>()
                .HasOptional(c => c.Parent)
                .WithMany()
                .HasForeignKey(c => c.Parent_Id)
                .WillCascadeOnDelete(false);

            modelBuilder.Entity<Comment>()
                .HasRequired(c => c.Author)
                .WithMany()
                .HasForeignKey(c => c.Author_UserId)
                .WillCascadeOnDelete(false);

            modelBuilder.Entity<CommentVote>()
                .HasRequired(c => c.Voter)
                .WithMany()
                .HasForeignKey(c => c.Voter_UserId)
                .WillCascadeOnDelete(false);

            modelBuilder.Entity<NodeVote>()
                .HasRequired(c => c.Author)
                .WithMany()
                .HasForeignKey(c => c.Author_UserId)
                .WillCascadeOnDelete(false);


        }

        public override int SaveChanges()
        {
            DateTime now = DateTime.Now;

            // Set date added on any assertions being created.
            foreach (var entry in ChangeTracker.Entries<Node>().Where(e => e.State == EntityState.Added))
            {
                entry.Entity.DateAdded = now;
            }

            // Set date added on any comments being created.
            foreach (var entry in ChangeTracker.Entries<Comment>().Where(e => e.State == EntityState.Added))
            {
                entry.Entity.DateAdded = now;
            }

            return base.SaveChanges();
        }
    }
}